import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Image, View, Text } from '@tarojs/components';
// import Taro, { useDidShow } from '@tarojs/taro';
import Taro, { useRouter } from '@tarojs/taro';
import CardContainer from '../../components/cardContainer';
import VerticalSeparation from '../../components/VerticalSeparation';
import PageContainer from '../../components/pageContainer';
import InputNumber from './components/inputNumber';
import events from '../../utils/events';
import rightPng from '../../assets/right.png';
import localPng from '../../assets/local.png';
import PagefooterButton from '../../components/pagefooterButton';
import request from '../../common/request';
import { formatTimeDate, getImagePath } from '../../utils';
import PopupLayer from '../../components/popupLayer';
import SelectStall from './components/selectStall';
import './index.scss';

const remainingQuantityMap = {};
const numberFormat = (i)=>{
  const n = parseFloat(i.toFixed(2));
  return Number.isNaN(n) ? 0 : n;
}
function Index() {
  const router = useRouter();
  const ref = useRef(null);
  const [ consignorOrderProduct, setConsignorOrderProduct] = useState({});
  const [ stall, setStall] = useState({});
  const [ reservedQuantityMap, setReservedQuantityMap] = useState({});// 保存填写的预定量
  const [ allPrice, setAllPrice] = useState(0); // 总价格
  const [ all, setAll] = useState(0); // 总量
  // 编辑时详情
  const [ queryItem, setQueryItem] = useState({});
  const postData = useCallback(()=>{
    request({method : 'GET', tartget: 'consignorOrderProductQuery', data: {condition: {id: router.params.consignorOrderId}} }).then((data)=>{
      if (data.success) {
        // remainingQuantityMap
        data.model.orderSpecList.forEach(i => {
          remainingQuantityMap[i.productSpecId] = i.remainingQuantity
        });
        setConsignorOrderProduct(data.model);
      }
    });
    if (router.params.type !== 'edit') {
      request({method : 'GET', tartget: 'userStallUQuery', data: { condition: { isDefault: 1 }} }).then((data)=>{
        if (data.success) {
          setStall(data.model);
        }
      });
    }
    if (router.params.type === 'edit') {
      request({method : 'GET', tartget: 'userStallUQuery', data: { condition: { id: router.params.stallId }} }).then((data)=>{
        if (data.success) {
          setStall(data.model);
        }
      });
      request({method : 'GET', tartget: 'orderStallOrderQuery', data: {condition: {id: router.params.id}} }).then((data)=>{
        if (data.success) {
          const reservedQuantityMapTem = {};
          // 预定量
          data.model.stallOrderSpecList.forEach(i => {
            reservedQuantityMapTem[i.productSpecId] = i.reservedQuantity
          });
          setReservedQuantityMap(reservedQuantityMapTem);
          setQueryItem(data.model);
        }
      });
    }
  },[]);

  useEffect(()=>{
    postData();
  },[]);

  // init
  useEffect(()=>{
    postData();
  },[]);

  // 计算总件数和总价格
  useEffect(()=>{
    let sum = 0;// 总件数
    let allPrice_ = 0;// 总金额
    // setAllPrice
    // setAll
    queryItem?.stallOrderSpecList?.forEach((i)=>{
      sum += i.reservedQuantity;
      allPrice_ += (i.unitPrice*i.reservedQuantity);
    });
    setAllPrice(allPrice_);
    setAll(sum);
  },[queryItem]);

  const onSubmit = useCallback(()=>{
    if (!stall.id) {
      Taro.showToast({ title: '请选择收货档口', icon: 'none' });
      return;
    }
    // 新增和编辑构建的对象，有点区别
    let stallOrderSpecList = [];
    let url = '';
    // tian - yuan < kuc
    let check = true;// 检验
    for (let i = 0; i < Object.keys(reservedQuantityMap).length; i++) {
      const iem = reservedQuantityMap[Object.keys(reservedQuantityMap)[i]];
      if (!(iem === '0' || iem ==='') && Number.isNaN(parseFloat(iem))) {
        Taro.showToast({ title: '预订量填写不正确', icon: 'none' });
        return;
      }
    }
    if(router.params.type === 'edit') {
      url = 'orderStallOrderUpdate';
      stallOrderSpecList = queryItem.stallOrderSpecList.map((i)=>{
        const iem = {...i};
        iem.reservedQuantity = reservedQuantityMap[i.productSpecId];
        return iem;
      }).filter((i)=>i.reservedQuantity && parseFloat(i.reservedQuantity) !== 0);
      // 校验
      for (let i = 0; i < queryItem.stallOrderSpecList.length; i++) {
        const itemTem = queryItem.stallOrderSpecList[i];
        // todo 原预定量 + 库存 > 填的预定量 >0
        if (!(itemTem.reservedQuantity + remainingQuantityMap[itemTem.productSpecId] >= parseFloat(reservedQuantityMap[itemTem.productSpecId] || 0) && reservedQuantityMap[itemTem.productSpecId] > 0)){
          Taro.showToast({ title: `抱歉，您所选择的规格${i+1}余量不足`, icon: 'none' });// 商品${i+1}预订增量不能大于库存
          return;
        }
      }
    } else {
      url = 'orderStallOrderAdd';
      stallOrderSpecList = consignorOrderProduct.orderSpecList.map((i)=>{
        const iem = {...i};
        iem.consignorOrderSpecId = iem.id;
        delete iem.id;
        iem.reservedQuantity = reservedQuantityMap[i.productSpecId];
        //
        if (reservedQuantityMap[i.productSpecId] > i.remainingQuantity) {
          check = false;
        }
        return iem;
      }).filter((i)=>i.reservedQuantity && parseFloat(i.reservedQuantity) !== 0);// '0.000000'
      if (!check){
        Taro.showToast({ title: '预订量不能大于库存', icon: 'none' });
        return;
      }
    }
    if (stallOrderSpecList.length === 0) {
      Taro.showToast({ title: '请填写预订量', icon: 'none' });
      return;
    }
    const parms = {
      stallOrderSpecList,
      stallId: stall.id,
      id: queryItem.id,
      consignorOrderId: consignorOrderProduct.id,
      productId:consignorOrderProduct.productId,
    };
    request({method : 'POST', tartget: url, data:[parms]}).then((data)=>{
      if (data.success) {
        if (router.params.type === 'edit'){
          events.emit('order-page-flush');
          Taro.navigateBack();
        } else {
          // 新增
          Taro.redirectTo({
            url:`/pages/order/index`,
          });
        }
      }
    });
  },[consignorOrderProduct, stall, reservedQuantityMap]);

  const inputOnChange = (id,value) =>{
    const reservedQuantityMapTem = {...reservedQuantityMap};
    reservedQuantityMapTem[id] = value;
    // setAllPrice
    let sum = 0;// 总金额
    let allTem = 0;// 总数量
    consignorOrderProduct.orderSpecList.forEach((i)=>{
      sum += (i.unitPrice * parseFloat(reservedQuantityMapTem[i.productSpecId] || 0));
      allTem += parseFloat(reservedQuantityMapTem[i.productSpecId] || 0);
    });
    setAllPrice(sum);
    setAll(allTem);
    setReservedQuantityMap(reservedQuantityMapTem);
  }

  const selectStallOpen = ()=>{
    ref.current.show();
  }

  const selectStallOnChange = (i)=>{
    ref.current.close();
    setStall(i);
  }
  return (
    <View>
      <PageContainer noPadding>
        <VerticalSeparation topSeparaton />
        <CardContainer>
          <View className='top' onClick={selectStallOpen}>
            <Image
              className='left-img'
              src={localPng}
            />
            {
              stall.id ? (
                <View className='middle'>
                  <View>
                    <Text className='middle-text1'>{stall.receiverName}</Text>
                    <Text className='middle-text2'>{stall.receiverPhoneNumber}</Text>
                  </View>
                  <View>{stall.marketName}|{stall.stallCode}档口</View>
                </View>
              ): (
                <View className='middle'>
                  <View>
                    <Text className='middle-text1'>请选择档口</Text>
                  </View>
                  <View>{stall.marketName}</View>
                </View>
              )
            }
            <Image
              className='right-img'
              src={rightPng}
            />
          </View>
        </CardContainer>
        <VerticalSeparation />
        <View className='body'>
          <View className='title'>
            {/*<Image
              className='title-img'
              src={shuiguoPng}
            />*/}
            <Text >{consignorOrderProduct?.consignorUser?.subjectName}</Text>
          </View>
          <View className='productDetail'>
            {
              consignorOrderProduct.productCoverId && (
                <Image
                  className='img'
                  src={getImagePath(consignorOrderProduct.productCoverId,consignorOrderProduct.productCoverCode)}
                />
              )
            }
            <View className='right-body'>
              <View className='right-body-text1'>{consignorOrderProduct.productName}</View>
              <View className='right-body-text2'>
                {`${consignorOrderProduct?.orderProduct?.originRegion} ${consignorOrderProduct?.orderProduct?.originCity} ${consignorOrderProduct?.orderProduct?.originArea}`}
              </View>
              <View className='right-body-text2'>预计{formatTimeDate(consignorOrderProduct.expectArriveTime)}到货</View>
            </View>
          </View>
          <View className='guiGe'>
            <View className='title'>
              <Text className='title-line1'>规格</Text>
              <Text className='title-line2'>指导价</Text>
              <Text className='title-line3'>预订量(件)</Text>
            </View>
            {
              consignorOrderProduct.orderSpecList &&
              consignorOrderProduct.orderSpecList.map((i)=>{
                return (
                  <View className='row'>
                    <View className='row-line1'>
                      <View className='text1'>{i.spec}</View>
                      <View className='text2'>库存:{i.remainingQuantity}件</View>
                    </View>
                    <Text className='row-line2'>￥{i.unitPrice}</Text>
                    <View className='row-line3'>
                      <InputNumber value={reservedQuantityMap[i.productSpecId]} onChange={inputOnChange.bind(this,i.productSpecId)} />
                    </View>
                  </View>
                );
              })
            }
          </View>
          <View className='count'>
            共计：¥{numberFormat(allPrice)}
          </View>
        </View>
      </PageContainer>
      <PagefooterButton
        leftButton={{
          textRender:(
            <View className='foodButton'>
              <View>
                <Text className='text1'>合计：</Text>
                <Text className='text2'>¥{numberFormat(allPrice)}</Text>
              </View>
              <View className='text3'>共{numberFormat(all)}件商品</View>
            </View>
          ),
        }}
        rightButton={{
          text:'提交代卖',
          onClick:onSubmit,
        }}
      />
      <PopupLayer
        id='popupRef'
        direction='top'
        ref={ref}
      >
        <view className='modalBox'>
          <SelectStall onChange={selectStallOnChange} />
        </view>
      </PopupLayer>
    </View>
  );
}

export default Index;
